package org.gulugulubiao.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.gulugulubiao.constant.JwtClaimsConstant;
import org.gulugulubiao.dto.UserLoginDTO;
import org.gulugulubiao.entity.User;
import org.gulugulubiao.mapper.UserMapper;
import org.gulugulubiao.properties.JwtProperties;
import org.gulugulubiao.result.Result;
import org.gulugulubiao.service.Impl.UserServiceImpl;
import org.gulugulubiao.service.UserService;
import org.gulugulubiao.utils.JwtUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {
    private final UserService userService;
    private final JwtProperties jwtProperties;
    private final UserMapper userMapper;
    private final UserServiceImpl userServiceImpl;


    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginDTO> userLogin(@RequestBody UserLoginDTO userLoginDTO) {

        log.info("用户登录：{}", userLoginDTO);

        User user = userServiceImpl.login(userLoginDTO);

        // JWT令牌校验
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        log.info("JWT签名秘钥: {}, 过期时间: {}", jwtProperties.getSignKey(), jwtProperties.getExpire());
        String token = JwtUtils.createJWT(
                jwtProperties.getSignKey(),
                jwtProperties.getExpire(),
                claims);

        UserLoginDTO userLoginDTOTemp = new UserLoginDTO().builder()
                .id(user.getId())
                .username(user.getUsername())
                .password(user.getPassword())
                .token(token)
                .role(user.getRole())
                .build();

        return Result.success(userLoginDTOTemp,"用户登录成功！");
    }


    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result userRegister(@RequestBody User user) {
        log.info("新增用户：{}",user);
        userService.add(user);
        return Result.success("新增用户成功！");
    }


    /**
     * 管理员新增用户
     * @param user
     * @return
     */
    @PostMapping("/add")
    public Result userInsert(@RequestBody User user){
        log.info("新增用户：{}",user);
        userService.userInsert(user);
        return Result.success("新增用户成功！");
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @DeleteMapping("/delete/{userId}")
    public Result userDelete(@PathVariable Integer userId){
        log.info("删除用户id：{}",userId);
        userService.userDelete(userId);
        return Result.success("删除用户成功！");
    }

}
